package com.epam.text_elements;

import java.util.ArrayList;
import java.util.List;

import com.epam.matchers.PunctuationMarkMatcher;
import com.epam.matchers.WordMatcher;

public class Sentence {
	private List<SentenceComponent> body=new ArrayList<SentenceComponent>();
	private int numOfWords;
	private int nextComponentPosition;

	public Sentence(String sentenceStr) {
		WordMatcher wordMatcher = new WordMatcher(sentenceStr);
		PunctuationMarkMatcher punctMarkMatcher = new PunctuationMarkMatcher(
				sentenceStr);
		numOfWords = wordMatcher.countWords();
		nextComponentPosition=0;
		Word nextWord;
		PunctuationMark nextMark;
		while (nextComponentPosition<sentenceStr.length()) {
			nextWord=wordMatcher.getNextWord(nextComponentPosition);
			nextMark=punctMarkMatcher.getNextPunctationMark(
					nextComponentPosition);
			//if the next punct. mark appears before the next word or 
			//there is no next word, add the mark
			if (wordMatcher.getStartNext()>punctMarkMatcher.getStartNext() |
					nextWord==null) {
				nextComponentPosition=punctMarkMatcher.getStartNext();
				body.add(nextMark);
			}
			//if the next word appears before the next punct. mark
			//add the word
			else {
				nextComponentPosition=wordMatcher.getStartNext();
				body.add(nextWord);
			}
		}
	}

	public int getNumOfWords() {
		return numOfWords;
	}

	@Override
	public String toString() {
		String res="";
		for (SentenceComponent component:body) {
			res+=component;
		}
		return res;
	}
}
